/*
 * @Author: Wangjun
 * @Date: 2022-10-14 16:27:24
 * @LastEditTime: 2022-10-14 16:35:24
 * @LastEditors: Wangjun
 * @Description:
 * @FilePath: \libs\apps\app_windows.go
 * hnxr
 */
package apps

import (
	"os/exec"
	"syscall"
	"unsafe"
)

// 显示或隐藏窗口
const (
	SwHide = 0
	SwShow = 5
)

// ShowWindow 显示窗口
func ShowConsoleWindow(show bool) {
	kdll, err := syscall.LoadDLL("kernel32.dll")
	if err != nil {
		return
	}
	defer kdll.Release()

	GetConsoleTitle, err := kdll.FindProc("GetConsoleTitleW")
	if err != nil {
		return
	}
	name := make([]uint16, 300)
	n, _, _ := GetConsoleTitle.Call(uintptr(unsafe.Pointer(&name[0])), uintptr(uint32(len(name))))
	if n == 0 {
		return
	}
	//name := string(utf16.Decode(uname[0:n]))

	dll, err := syscall.LoadDLL("user32.dll")
	if err != nil {
		return
	}
	defer dll.Release()

	FindWindow, err := dll.FindProc("FindWindowW")
	if err != nil {
		return
	}

	ShowWindow, err := dll.FindProc("ShowWindow")
	if err != nil {
		return
	}

	hwnd, _, _ := FindWindow.Call(uintptr(0), uintptr(unsafe.Pointer(&name[0])))
	if hwnd == 0 {
		return
	}

	if show {
		ShowWindow.Call(uintptr(hwnd), uintptr(SwShow))
	} else {
		ShowWindow.Call(uintptr(hwnd), uintptr(SwHide))
	}
}

// Reboot 重启系统
func Reboot() (err error) {
	cmd := exec.Command("shutdown", "-r", "-t", "10")
	return cmd.Start()
}
